//
//  BCImageresizerController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/27.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCImageresizerController.h"

//裁减框架
#import <JPImageresizerView.h>
#import <JPImageresizerFrameView.h>
//
#import "UIImage+ResizeImage.h"
#import "UIButton+UIActivityIndicatorView.h"

@interface BCImageresizerBottomView : UIView

/**
 *contentView
 */
@property (nonatomic, strong) UIView *contentView;

/**
 *cancelButton
 */
@property (nonatomic, strong) QMUIButton *cancelButton;

/**
 *doneButton
 */
@property (nonatomic, strong) QMUIButton *doneButton;

/**
 *recoveryButton
 */
@property (nonatomic, strong) QMUIButton *recoveryButton;

@end

@implementation BCImageresizerBottomView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    UIView *topLine = [UIView new];
    topLine.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
    [self addSubview:topLine];
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self);
        make.height.mas_equalTo(.5);
    }];
    self.contentView = [UIView new];
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self);
        make.height.mas_equalTo([self.class contentHeight]);
    }];
    //
    self.cancelButton = [QMUIButton new];
    [self.contentView addSubview:self.cancelButton];
    //
    self.recoveryButton = [QMUIButton new];
    [self.contentView addSubview:self.recoveryButton];
    //
    self.doneButton = [QMUIButton new];
    [self.contentView addSubview:self.doneButton];
    //
    [self.cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.recoveryButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //
    self.cancelButton.titleLabel.font = self.recoveryButton.titleLabel.font = self.doneButton.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    self.cancelButton.titleEdgeInsets = self.recoveryButton.titleEdgeInsets = self.doneButton.titleEdgeInsets = UIEdgeInsetsMake(3, 20, 3, 20);
    //
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.contentView);
        make.left.mas_equalTo(self.contentView);
    }];
    [self.recoveryButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(self.contentView);
    }];
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.contentView);
        make.right.mas_equalTo(self.contentView);
    }];
    
    
    //
    [self.cancelButton setTitle:BCLocalizedKey(@"general_cancel") forState:UIControlStateNormal];
    [self.recoveryButton setTitle:BCLocalizedKey(@"general_recovery") forState:UIControlStateNormal];
    [self.doneButton setTitle:BCLocalizedKey(@"general_complete") forState:UIControlStateNormal];
}

+ (CGFloat)contentHeight {
    return 49.0;
}
+ (CGFloat)defaultHeight {
    return [self contentHeight]+Height_Bottom_SafeArea;
}

@end

@interface BCImageresizerController ()

@property (nonatomic, strong) JPImageresizerView *imageresizerView;
/**
 *imageresizerViewScroll
 */
@property (nonatomic, weak) UIScrollView *imageresizerViewScroll;
/**
 *JPImageresizerFrameView
 */
@property (nonatomic, weak) JPImageresizerFrameView *imageresizerFrameView;

/**
 *BCImageresizerBottomView
 */
@property (nonatomic, strong) BCImageresizerBottomView *bottomView;

/**
 *rotateButton
 */
@property (nonatomic, strong) QMUIButton *rotateButton;

@end

@implementation BCImageresizerController

#pragma mark - 返回
/// 是否需要拦截系统返回按钮的事件，只有当这里返回YES的时候，才会询问方法：`canPopViewController`
- (BOOL)shouldHoldBackButtonEvent {
    return true;
}
/// 是否可以`popViewController`，可以在这个返回里面做一些业务的判断，比如点击返回按钮的时候，如果输入框里面的文本没有满足条件的则可以弹alert并且返回NO
- (BOOL)canPopViewController {
    return false;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.customNaviBar.backgroundColor = [UIColor blackColor];
    self.customNaviBar.hidden = true;
    //
    [self setupSubviews];
    //
    for (UIView *subView in self.imageresizerView.subviews) {
        if ([subView isKindOfClass:UIScrollView.class]) {
            self.imageresizerViewScroll = (UIScrollView *)subView;
        }
        if ([subView isKindOfClass:JPImageresizerFrameView.class]) {
            self.imageresizerFrameView = (JPImageresizerFrameView *)subView;
        }
    }
    //kvo
    [self addObservers];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.navigationController) {
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }//
    if (!self.navigationController.navigationBar.hidden) {
        [self.navigationController setNavigationBarHidden:true animated:true];
    }
}
//
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //
    if (self.imageresizerView.resizeWHScale!=1) {
        [self.imageresizerView setResizeWHScale:1 animated:true];
    }
}


- (void)setupSubviews {
    CGSize imageSize = self.image.size;
    //
    CGRect frame = self.view.bounds;
    /** 遮罩样式，目前初始化后不可再更改 */
    JPImageresizerMaskType maskType = JPNormalMaskType;
    /** 边框样式 */
    JPImageresizerFrameType frameType = JPClassicFrameType;
    /** 动画曲线（默认是线性Linear） */
    JPAnimationCurve animationCurve = JPAnimationCurveEaseInOut;
    /** 裁剪线颜色 */
    UIColor *strokeColor = [UIColor whiteColor];
    /** 背景颜色 */
    UIColor *bgColor = [UIColor blackColor];
    /** 遮罩颜色的透明度（背景颜色 * 透明度） */
    CGFloat maskAlpha = 0.5;
    /** 裁剪宽高比（0则为任意比例，可控8个方向，固定比例为4个方向） */
    CGFloat resizeWHScale = imageSize.width/imageSize.height;
    /** 裁剪图片与裁剪区域的垂直边距 */
    CGFloat verBaseMargin = 200;
    /** 裁剪图片与裁剪区域的水平边距 */
    CGFloat horBaseMargin = 50;
    //
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    /** 是否顺时针旋转（默认逆时针） */
    BOOL isClockwiseRotation = true;
    /** 是否锁定裁剪区域（锁定后无法拖动裁剪区域） */
    BOOL isLockResizeFrame = false;
    //
    self.imageresizerView = [[JPImageresizerView alloc] initWithResizeImage:self.image
                                                                      frame:frame
                                                                   maskType:maskType
                                                                  frameType:frameType
                                                             animationCurve:animationCurve
                                                                strokeColor:strokeColor
                                                                    bgColor:bgColor
                                                                  maskAlpha:maskAlpha
                                                              verBaseMargin:verBaseMargin
                                                              horBaseMargin:horBaseMargin
                                                              resizeWHScale:resizeWHScale
                                                              contentInsets:contentInsets
                                                  imageresizerIsCanRecovery:^(BOOL isCanRecovery) {
                                                      
                                                  } imageresizerIsPrepareToScale:^(BOOL isPrepareToScale) {
                                                      
                                                  }];
    self.imageresizerView.isClockwiseRotation = isClockwiseRotation;
    self.imageresizerView.isLockResizeFrame = isLockResizeFrame;
    [self.view addSubview:self.imageresizerView];
    //
    self.bottomView = [BCImageresizerBottomView new];
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.height.mas_equalTo([BCImageresizerBottomView defaultHeight]);
    }];
    //
    [self.bottomView.cancelButton addTarget:self action:@selector(cancelButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView.recoveryButton addTarget:self action:@selector(recoveryButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView.doneButton addTarget:self action:@selector(doneButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    //
    self.rotateButton = [QMUIButton new];
    [self.rotateButton setImage:LOAD_IMAGE(@"user_head_rotation") forState:UIControlStateNormal];
    [self.view addSubview:self.rotateButton];
    [self.rotateButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view).offset(-20.0);
        make.top.mas_equalTo(self.view).offset(20.0+Height_StatusBar);
    }];
    [self.rotateButton addTarget:self action:@selector(rotateButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    //
    [self updateRecoveryButtonEnabled];
    [self updateDoneButtonEnabled];
}

#pragma mark - updates
//设置还原按钮可点击状态
- (void)updateRecoveryButtonEnabled {
    self.bottomView.recoveryButton.enabled = self.imageresizerFrameView.isCanRecovery;
}
//设置完成按钮可点击状态
- (void)updateDoneButtonEnabled {
    self.bottomView.doneButton.enabled = !self.imageresizerFrameView.isPrepareToScale;
    //
    if (self.imageresizerFrameView.isPrepareToScale) {//隐藏rotate
        [UIView animateWithDuration:0.2 animations:^{
            self.rotateButton.alpha = 0;
        }];
    }else {//显示
        [UIView animateWithDuration:0.2 animations:^{
            self.rotateButton.alpha = 1;
        }];
    }
}

#pragma mark - action
- (void)cancelButtonDidClickedAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(imageresizerControllerDidClickedCancelAction)]) {
        [self.delegate imageresizerControllerDidClickedCancelAction];
    }
    [self didClickedNaviLeftButton];
}
- (void)rotateButtonDidClickedAction {
    
    [self.imageresizerView rotation];
}
- (void)recoveryButtonDidClickedAction {
    if (!self.imageresizerFrameView.isPrepareToScale) {
        [self.imageresizerView recovery];
    }
}
- (void)doneButtonDidClickedAction {
    if (self.imageresizerViewScroll) {
        if (self.imageresizerViewScroll.isTracking||self.imageresizerViewScroll.isDragging||self.imageresizerViewScroll.decelerating) {
            return;
        }
    }
    //开始裁减image
    [self.view setUserInteractionEnabled:false];
    [self showImageResizerLoading];
    [self.imageresizerView originImageresizerWithComplete:^(UIImage *resizeImage) {
        /**
         处理图片 压缩和重置大小
         */
        //        UIImage *handleImage = resizeImage;
        //        //压缩图片尺寸
        //        CGSize size = CGSizeMake(ScreenWidth, ScreenWidth);
        //        if (resizeImage.size.width<ScreenWidth) {
        //            size.width = resizeImage.size.width;
        //            size.height = resizeImage.size.height;
        //        }
        //        UIGraphicsBeginImageContext(size);
        //        [handleImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        //        UIImage *tempSizeImage = UIGraphicsGetImageFromCurrentImageContext();
        //        UIGraphicsEndImageContext();
        //
        NSData *resultData = [UIImage compressImageData:resizeImage limitLength:128.0];
        UIImage *resultImage = [UIImage imageWithData:resultData];
        //多线程 返回main
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.view setUserInteractionEnabled:true];
            [self finishedImageresizer:resultImage];
        });
    }];
}
//显示裁减加载过程
- (void)showImageResizerLoading {
    self.rotateButton.alpha = 0;
    self.bottomView.cancelButton.enabled = false;
    self.bottomView.recoveryButton.enabled = false;
    self.bottomView.doneButton.enabled = false;
    //
    [self.view bc_showActivityIndicatorBackgroundColor:[UIColor clearColor] insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
}


- (void)finishedImageresizer:(UIImage *)resizeImage {
    if (self.delegate && [self.delegate respondsToSelector:@selector(imageresizerControllerDidResizeredWithImage:)]) {
        [self.delegate imageresizerControllerDidResizeredWithImage:resizeImage];
    }
    [self didClickedNaviLeftButton];
}


#pragma mark - KVO
- (void)addObservers {
    if (self.imageresizerFrameView) {
        [self.imageresizerFrameView addObserver:self forKeyPath:NSStringFromSelector(@selector(isCanRecovery)) options:NSKeyValueObservingOptionNew context:nil];
        [self.imageresizerFrameView addObserver:self forKeyPath:NSStringFromSelector(@selector(isPrepareToScale)) options:NSKeyValueObservingOptionNew context:nil];
    }
}
- (void)removeObservers {
    if (self.imageresizerFrameView) {
        [self.imageresizerFrameView removeObserver:self forKeyPath:NSStringFromSelector(@selector(isCanRecovery))];
        [self.imageresizerFrameView removeObserver:self forKeyPath:NSStringFromSelector(@selector(isPrepareToScale))];
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(isCanRecovery))]) {//还原按钮状态
        [self updateRecoveryButtonEnabled];
    }
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(isPrepareToScale))]) {
        [self updateDoneButtonEnabled];
    }
}



- (void)dealloc {
    [self removeObservers];
}

@end
